--[[ =========================================================================
   ROUE ROCKET -- la roue gratuite quotidienne, pour CC:Tweaked
   -------------------------------------------------------------------------
   A installer sur un ADVANCED COMPUTER avec :
     - un MONITEUR AVANCE tactile (6x5 blocs conseille) : la roue
     - un Wired Modem
     - client_solde.lua et login_term.lua sur le meme computer

   Un tour gratuit toutes les 24 heures pile. Tu lances a 17h35, tu
   pourras relancer demain a 17h35.

   LA SERIE : revenir chaque jour fait monter ton palier.
     jours 1-2  : roue de BRONZE   (environ 116 credits par tour)
     jours 3-6  : roue d'ARGENT    (environ 264)
     jour 7+    : roue MASTER BALL (environ 955)
   Rater plus de 48 heures remet la serie a zero. C'est ce qui fait
   revenir les joueurs tous les jours, bien plus qu'une roue plate.
========================================================================= ]]

--------------------------------------------------------------------------
-- CONFIGURATION
--------------------------------------------------------------------------
local CFG = {
  cooldown   = 24 * 3600 * 1000,   -- 24 h en millisecondes
  streakGrace= 48 * 3600 * 1000,   -- au-dela, la serie repart de zero
  dataFile   = "roue_data.dat",
  fps        = 15,
  spinTime   = 6.0,                -- duree de la rotation
  resultTime = 7.0,
  monitorName = nil,
}

-- Les trois roues. "REJOUE" relance un tour, "MIAOUSS" vole la
-- recompense (avec une consolation).
local WHEELS = {
  bronze = {
    label = "BRONZE", ring = "1", need = 1,
    seg = { 50, 100, 25, 200, 75, "REJOUE", 50, 500, 100, "MIAOUSS", 25, 150 },
    consol = 10,
  },
  argent = {
    label = "ARGENT", ring = "3", need = 3,
    seg = { 150, 250, 100, 400, 200, "REJOUE", 150, 1000, 250, "MIAOUSS",
            100, 300 },
    consol = 25,
  },
  master = {
    label = "MASTER BALL", ring = "a", need = 7,
    seg = { 400, 700, 300, 1200, 600, "REJOUE", 400, 5000, 700, "MIAOUSS",
            300, 900 },
    consol = 50,
  },
}

local function wheelFor(streak)
  if streak >= WHEELS.master.need then return WHEELS.master, "master" end
  if streak >= WHEELS.argent.need then return WHEELS.argent, "argent" end
  return WHEELS.bronze, "bronze"
end

--------------------------------------------------------------------------
-- PERIPHERIQUES
--------------------------------------------------------------------------
local bank  = dofile("client_solde.lua")
local login = dofile("login_term.lua")

local mon
if CFG.monitorName then mon = peripheral.wrap(CFG.monitorName)
else mon = peripheral.find("monitor") end
if not mon then error("Aucun moniteur trouve (il doit etre avance).", 0) end

local speaker = peripheral.find("speaker")
local function beep(p, inst)
  if speaker then pcall(speaker.playNote, inst or "bit", 1, p or 12) end
end

--------------------------------------------------------------------------
-- PALETTE ET FRAMEBUFFER
--------------------------------------------------------------------------
local PAL = {
  ["0"] = 0xffffff, ["1"] = 0xff7a18, ["2"] = 0xff2f8f, ["3"] = 0xc3c7d4,
  ["4"] = 0xffd23f, ["5"] = 0x9dff5c, ["6"] = 0xff5fb0, ["7"] = 0x14141c,
  ["8"] = 0x3c3c4a, ["9"] = 0x2fa3f0, ["a"] = 0x8b5cd6, ["b"] = 0x1b3a8f,
  ["c"] = 0x7a0f16, ["d"] = 0x2fa84f, ["e"] = 0xd11f2a, ["f"] = 0x000000,
}

mon.setTextScale(0.5)
for hex, rgb in pairs(PAL) do
  pcall(mon.setPaletteColour, 2 ^ tonumber(hex, 16), rgb)
end

local W, H = mon.getSize()
local ct, cf, cb = {}, {}, {}

local function fbInit()
  W, H = mon.getSize()
  ct, cf, cb = {}, {}, {}
  for y = 1, H do ct[y], cf[y], cb[y] = {}, {}, {} end
end

local function clear(bg)
  bg = bg or "f"
  for y = 1, H do
    for x = 1, W do ct[y][x], cf[y][x], cb[y][x] = " ", "f", bg end
  end
end

local function px(x, y, bg)
  x, y = math.floor(x), math.floor(y)
  if x >= 1 and x <= W and y >= 1 and y <= H then
    ct[y][x], cf[y][x], cb[y][x] = " ", "f", bg
  end
end

local function rect(x1, y1, x2, y2, bg)
  for y = math.floor(y1), math.floor(y2) do
    for x = math.floor(x1), math.floor(x2) do px(x, y, bg) end
  end
end

local function text(x, y, s, fg, bg)
  x, y = math.floor(x), math.floor(y)
  for i = 1, #s do
    local xx = x + i - 1
    if xx >= 1 and xx <= W and y >= 1 and y <= H then
      ct[y][xx] = s:sub(i, i)
      cf[y][xx] = fg or "0"
      if bg then cb[y][xx] = bg end
    end
  end
end

local function center(x1, x2, y, s, fg, bg)
  text(math.floor(x1 + ((x2 - x1 + 1) - #s) / 2), y, s, fg, bg)
end

local function push()
  for y = 1, H do
    mon.setCursorPos(1, y)
    mon.blit(table.concat(ct[y]), table.concat(cf[y]), table.concat(cb[y]))
  end
end

fbInit()

--------------------------------------------------------------------------
-- FONTE 5x7
--------------------------------------------------------------------------
local FONT = {
  R="11110/10001/10001/11110/10100/10010/10001",
  O="01110/10001/10001/10001/10001/10001/01110",
  U="10001/10001/10001/10001/10001/10001/01110",
  E="11111/10000/10000/11110/10000/10000/11111",
  C="01110/10001/10000/10000/10000/10001/01110",
  K="10001/10010/10100/11000/10100/10010/10001",
  T="11111/00100/00100/00100/00100/00100/00100",
  G="01110/10001/10000/10111/10001/10001/01111",
  A="01110/10001/10001/11111/10001/10001/10001",
  I="11111/00100/00100/00100/00100/00100/11111",
  S="01111/10000/10000/01110/00001/00001/11110",
  N="10001/11001/10101/10011/10001/10001/10001",
  M="10001/11011/10101/10101/10001/10001/10001",
  B="11110/10001/10001/11110/10001/10001/11110",
  L="10000/10000/10000/10000/10000/10000/11111",
  D="11110/10001/10001/10001/10001/10001/11110",
  P="11110/10001/10001/11110/10000/10000/10000",
  V="10001/10001/10001/10001/10001/01010/00100",
  X="10001/10001/01010/00100/01010/10001/10001",
  J="00111/00010/00010/00010/00010/10010/01100",
  ["!"]="00100/00100/00100/00100/00100/00000/00100",
  ["+"]="00000/00100/00100/11111/00100/00100/00000",
  ["0"]="01110/10011/10101/10101/11001/10001/01110",
  ["1"]="00100/01100/00100/00100/00100/00100/01110",
  ["2"]="01110/10001/00001/00110/01000/10000/11111",
  ["3"]="11111/00010/00100/00010/00001/10001/01110",
  ["4"]="00010/00110/01010/10010/11111/00010/00010",
  ["5"]="11111/10000/11110/00001/00001/10001/01110",
  ["6"]="00110/01000/10000/11110/10001/10001/01110",
  ["7"]="11111/00001/00010/00100/01000/01000/01000",
  ["8"]="01110/10001/10001/01110/10001/10001/01110",
  ["9"]="01110/10001/10001/01111/00001/00010/01100",
  [" "]="00000/00000/00000/00000/00000/00000/00000",
}
local GLYPH = {}
for ch, def in pairs(FONT) do
  local rows = {}
  for r in def:gmatch("[^/]+") do rows[#rows + 1] = r end
  GLYPH[ch] = rows
end

local function bigWidth(s, sx) sx = sx or 1; return #s * (5 * sx + sx) - sx end

local function bigText(x0, y0, s, colFn, sx, sy)
  sx, sy = sx or 1, sy or 1
  local cx = x0
  for i = 1, #s do
    local g = GLYPH[s:sub(i, i)] or GLYPH[" "]
    for ry = 1, 7 do
      for rx = 1, 5 do
        if g[ry]:sub(rx, rx) == "1" then
          for iy = 0, sy - 1 do
            for ix = 0, sx - 1 do
              px(cx + (rx - 1) * sx + ix, y0 + (ry - 1) * sy + iy,
                 colFn(cx + (rx - 1) * sx + ix, ry))
            end
          end
        end
      end
    end
    cx = cx + 5 * sx + sx
  end
end

--------------------------------------------------------------------------
-- DONNEES PERSISTANTES
--------------------------------------------------------------------------
local function loadData()
  if not fs.exists(CFG.dataFile) then return { players = {}, last = {} } end
  local f = fs.open(CFG.dataFile, "r")
  local d = textutils.unserialize(f.readAll() or "")
  f.close()
  if type(d) ~= "table" then return { players = {}, last = {} } end
  d.players = d.players or {}
  d.last = d.last or {}
  return d
end

local function saveData(d)
  local f = fs.open(CFG.dataFile, "w")
  f.write(textutils.serialize(d))
  f.close()
end

local DATA = loadData()

local function now() return os.epoch("utc") end

-- Retourne : peut jouer (bool), temps restant en ms, serie a venir
local function status(player)
  local p = DATA.players[player]
  if not p or not p.last then return true, 0, 1 end
  local gap = now() - p.last
  if gap < CFG.cooldown then
    return false, CFG.cooldown - gap, p.streak or 1
  end
  local streak = (gap <= CFG.streakGrace) and ((p.streak or 0) + 1) or 1
  return true, 0, streak
end

local function fmtDelay(ms)
  local s = math.floor(ms / 1000)
  local h = math.floor(s / 3600)
  local m = math.floor((s % 3600) / 60)
  local sec = s % 60
  if h > 0 then return string.format("%dh %02dm", h, m) end
  if m > 0 then return string.format("%dm %02ds", m, sec) end
  return sec .. "s"
end

local function fmt(n)
  local s = tostring(math.floor(n))
  local out = ""
  while #s > 3 do out = " " .. s:sub(-3) .. out; s = s:sub(1, -4) end
  return s .. out
end

local function recordSpin(player, streak, gain)
  local p = DATA.players[player] or { best = 0, total = 0 }
  p.last = now()
  p.streak = streak
  p.best = math.max(p.best or 0, streak)
  p.total = (p.total or 0) + gain
  DATA.players[player] = p
  table.insert(DATA.last, 1, { player = player, gain = gain, streak = streak })
  while #DATA.last > 8 do table.remove(DATA.last) end
  saveData(DATA)
end

local function topStreaks(n)
  local list = {}
  for name, p in pairs(DATA.players) do
    list[#list + 1] = { player = name, best = p.best or 0,
                        cur = p.streak or 0 }
  end
  table.sort(list, function(a, b) return a.best > b.best end)
  local out = {}
  for i = 1, math.min(n, #list) do out[i] = list[i] end
  return out
end

--------------------------------------------------------------------------
-- MISE EN PAGE
--------------------------------------------------------------------------
local L = {}
local function layout()
  fbInit()
  L.x1, L.y1, L.x2, L.y2 = 2, 2, W - 1, H - 1
  L.panelW = (W >= 74) and 28 or 0
  L.panelX = L.panelW > 0 and (L.x2 - L.panelW + 1) or nil
  L.wheelX2 = L.panelW > 0 and (L.panelX - 2) or L.x2
  L.headH = 10                       -- titre + bandeau GRATUIT
  L.cx = math.floor((L.x1 + L.wheelX2) / 2)
  -- 4 lignes reservees au curseur, sinon le bandeau le recouvre
  local top = L.y1 + L.headH + 4
  L.ry = math.max(6, math.min(math.floor((L.y2 - 2 - top) / 2), 19))
  L.cy = top + L.ry
  L.rx = math.min(math.floor(L.ry * 1.55),
                  math.floor((L.wheelX2 - L.x1) / 2) - 1)
end
layout()

--------------------------------------------------------------------------
-- LA ROUE
--------------------------------------------------------------------------
local SEG_COL = { "e", "4", "e", "4", "e", "4", "e", "4", "e", "4", "e", "4" }

-- Fond de scene : halo rouge derriere la roue, poussiere d'etoiles,
-- et un grand R en filigrane. Sans ca la roue flotte sur du noir.
local function drawBackdrop(t)
  -- Le halo ne sert que HORS de la roue : dessine dessous, il ne se
  -- voyait pas et brouillait la lecture des parts.
  for y = L.y1, L.y2 do
    for x = L.x1, L.x2 do
      local dx = (x - L.cx) / L.rx
      local dy = (y - L.cy) / L.ry
      local d = dx * dx + dy * dy
      if d > 1.05 then
        if d < 1.9 then px(x, y, "c")
        elseif d < 3.2 then px(x, y, "7")
        else px(x, y, "f") end
      else
        px(x, y, "f")
      end
    end
  end
  -- poussiere d'etoiles dans les coins sombres
  for i = 1, 60 do
    local sx = L.x1 + ((i * 37 + 13) % math.max(1, L.wheelX2 - L.x1))
    local sy = L.y1 + ((i * 23 + 7) % math.max(1, L.y2 - L.y1))
    local dx, dy = (sx - L.cx) / L.rx, (sy - L.cy) / L.ry
    if dx * dx + dy * dy > 3.0 and math.floor(t * 2 + i) % 5 ~= 0 then
      px(sx, sy, (i % 5 == 0) and "4" or "8")
    end
  end
end

local function segLabel(v)
  if v == "REJOUE" then return "REJOUE" end
  if v == "MIAOUSS" then return "MIAOUSS" end
  return tostring(v)
end

-- rot : angle de rotation de la roue. Le curseur est fixe, en haut.
local function drawWheel(wheel, rot, t, hotSeg)
  local n = #wheel.seg
  local seg = 2 * math.pi / n
  -- part designee par le curseur, elle s'eclaire
  local pointed = math.floor(((-rot) % (2 * math.pi)) / seg) % n

  local ratio = L.rx / L.ry
  for y = L.cy - L.ry - 2, L.cy + L.ry + 2 do
    for x = L.cx - L.rx - 2, L.cx + L.rx + 2 do
      local nx, ny = (x - L.cx) / L.rx, (y - L.cy) / L.ry
      local d = nx * nx + ny * ny
      if d <= 1.30 then
        local a = (math.atan2(nx, -ny) - rot) % (2 * math.pi)
        local idx = math.floor(a / seg) % n
        if d > 1.06 then
          local bulb = math.floor(a / (2 * math.pi) * 48 + t * 6) % 3
          px(x, y, (bulb == 0) and "4" or ((bulb == 1) and "1" or "c"))
        elseif d > 0.96 then
          px(x, y, "f")
        else
          local col = SEG_COL[idx + 1]
          local v = wheel.seg[idx + 1]
          if v == "MIAOUSS" then col = "8"
          elseif v == "REJOUE" then col = "d"
          elseif type(v) == "number" and v >= 500 then col = "a" end
          if idx == pointed then
            col = (col == "e") and "1" or ((col == "4") and "0" or col)
          end
          if hotSeg == idx and math.floor(t * 8) % 2 == 0 then col = "0" end
          px(x, y, col)
        end
      end
    end
  end

  -- Rayons noirs entre les parts. On les trace explicitement au lieu
  -- de tester un ecart d'angle : un test angulaire degenere des qu'une
  -- limite frole l'horizontale et noircit toute la ligne d'ecran.
  for i = 0, n - 1 do
    local a = rot + i * seg
    local sa, ca = math.sin(a), math.cos(a)
    local steps = math.max(L.rx, L.ry) * 2
    for k = 0, steps do
      local u = 0.16 + (k / steps) * 0.80
      px(L.cx + sa * L.rx * u, L.cy - ca * L.ry * u, "f")
    end
  end

  -- taquets sur la jante, un par part
  for i = 0, n - 1 do
    local a = rot + i * seg
    px(L.cx + math.sin(a) * L.rx * 1.02,
       L.cy - math.cos(a) * L.ry * 1.02, "3")
  end

  -- etiquettes au centre de chaque part
  for i = 0, n - 1 do
    local a = rot + (i + 0.5) * seg
    local lx = L.cx + math.sin(a) * L.rx * 0.62
    local ly = L.cy - math.cos(a) * L.ry * 0.62
    local lbl = segLabel(wheel.seg[i + 1])
    local half = math.floor(#lbl / 2)
    rect(lx - half - 1, ly, lx + half + 1, ly, "f")
    center(lx - half - 1, lx + half + 1, ly, lbl, "0", "f")
  end

  -- moyeu frappe du R
  for y = L.cy - 3, L.cy + 3 do
    for x = L.cx - 5, L.cx + 5 do
      local nx, ny = (x - L.cx) / 5, (y - L.cy) / 3
      if nx * nx + ny * ny <= 1 then px(x, y, "c") end
    end
  end
  center(L.cx - 2, L.cx + 2, L.cy, "R", "4", "c")

end

-- Curseur fixe en haut. Dessine apres les bandeaux, sinon le titre le
-- recouvrait. Il tressaute au passage de chaque taquet.
local function drawPointer(wheel, rot)
  local seg = 2 * math.pi / #wheel.seg
  local a = (-rot) % (2 * math.pi)
  local wob = ((a % seg) < seg * 0.20) and 1 or 0
  for k = 0, 3 do
    for dx = -(3 - k), (3 - k) do
      px(L.cx + dx, L.cy - L.ry - 4 + k + wob, (k == 3) and "e" or "4")
    end
  end
  px(L.cx, L.cy - L.ry - 1 + wob, "e")
end

--------------------------------------------------------------------------
-- BANDEAUX
--------------------------------------------------------------------------
local CHASE = { "4", "1", "e", "c" }
local function drawFrame(t, flash)
  local step = math.floor(t * 6)
  for x = 1, W do
    local a = flash and (((x + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((x + step) % 4) + 1]
    px(x, 1, a); px(x, H, a)
  end
  for y = 1, H do
    local a = flash and (((y + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((y + step) % 4) + 1]
    px(1, y, a); px(W, y, a)
  end
end

local function drawTitle(t, wheel)
  rect(L.x1, L.y1, L.x2, L.y1 + L.headH - 1, "f")
  local title = "ROUE ROCKET"
  local sc = (bigWidth(title, 2) <= (L.x2 - L.x1 - 2)) and 2 or 1
  local w = bigWidth(title, sc)
  local tx = L.x1 + math.floor(((L.x2 - L.x1 + 1) - w) / 2)
  local sweep = (t * 26) % (w + 70) - 35
  bigText(tx + 1, L.y1 + 1, title, function() return "f" end, sc, sc)
  bigText(tx, L.y1, title, function(x, gy)
    local d = x - tx - sweep
    if d > -2 and d < 2 then return "0" end
    if gy <= 3 then return "4" elseif gy <= 5 then return "1" else return "e" end
  end, sc, sc)

  -- la gratuite doit sauter aux yeux : bandeau pleine largeur qui clignote
  local blink = (math.floor(t * 2) % 2 == 0)
  local by = L.y1 + L.headH - 2
  rect(L.x1, by, L.x2, by + 1, blink and "5" or "d")
  center(L.x1, L.x2, by, "*** TOUR GRATUIT - UNE FOIS PAR JOUR ***",
         "f", blink and "5" or "d")
  center(L.x1, L.x2, by + 1,
         "TOUCHE L'ECRAN ET REPARS AVEC DES CREDITS", "f",
         blink and "5" or "d")
end

local function drawPanel(t, player, streak, wheel, waitMs)
  if L.panelW == 0 then return end
  local x1, x2 = L.panelX, L.x2
  rect(x1 - 1, L.y1 + L.headH, x2, L.y2, "7")

  local y = L.y1 + L.headH + 1

  -- 1. mode d'emploi, toujours affiche : c'est la premiere chose que
  -- doit comprendre quelqu'un qui passe devant
  rect(x1, y, x2, y, "e")
  center(x1, x2, y, "COMMENT CA MARCHE", "4", "e")
  y = y + 1
  text(x1, y,     "1. Connecte-toi au", "0"); y = y + 1
  text(x1, y,     "   terminal a cote", "0"); y = y + 1
  text(x1, y,     "2. Touche l'ecran", "0"); y = y + 1
  text(x1, y,     "3. Empoche tes credits", "0"); y = y + 2

  -- 2. les trois paliers, celui en cours mis en avant
  rect(x1, y, x2, y, "e")
  center(x1, x2, y, "LES TROIS ROUES", "4", "e")
  y = y + 1
  local tiers = {
    { WHEELS.bronze, "1j", "500" },
    { WHEELS.argent, "3j", "1000" },
    { WHEELS.master, "7j", "5000" },
  }
  for _, e in ipairs(tiers) do
    local w = e[1]
    local here = (wheel and wheel.label == w.label)
    if here then rect(x1, y, x2, y, "c") end
    text(x1, y, (here and ">" or " ") .. w.label, here and "4" or w.ring,
         here and "c" or nil)
    local right = e[2] .. "  max " .. e[3]
    text(x2 - #right + 1, y, right, here and "0" or "8",
         here and "c" or nil)
    y = y + 1
  end
  y = y + 1

  -- 3. la serie du joueur, en gros
  rect(x1, y, x2, y, "e")
  center(x1, x2, y, "TA SERIE", "4", "e")
  y = y + 1
  if player then
    center(x1, x2, y, player, "0")
    local sTxt = tostring(streak or 1)
    local w = bigWidth(sTxt, 2)
    bigText(x1 + math.floor((L.panelW - w) / 2), y + 1, sTxt,
            function(_, gy) return gy <= 3 and "4" or "1" end, 2, 2)
    center(x1, x2, y + 15, (streak == 1) and "jour" or "jours d'affilee", "3")
    y = y + 17
    local nextNeed
    if wheel.label == "BRONZE" then nextNeed = WHEELS.argent.need
    elseif wheel.label == "ARGENT" then nextNeed = WHEELS.master.need end
    if nextNeed then
      center(x1, x2, y, "encore " .. (nextNeed - streak) ..
             " jour(s) pour mieux", "5")
    else
      center(x1, x2, y, "palier maximum !", "5")
    end
    y = y + 2
  else
    center(x1, x2, y, "personne connecte", "8")
    y = y + 2
  end

  if waitMs and waitMs > 0 then
    rect(x1, y, x2, y, "8")
    center(x1, x2, y, "PROCHAIN TOUR DANS", "0", "8")
    center(x1, x2, y + 1, fmtDelay(waitMs), "4")
    y = y + 3
  end

  -- 4. classement des series et derniers gains, si la place reste
  if y + 2 <= L.y2 then
    rect(x1, y, x2, y, "e")
    center(x1, x2, y, "PLUS LONGUES SERIES", "4", "e")
    y = y + 1
    local top = topStreaks(3)
    for i, e in ipairs(top) do
      if y > L.y2 then break end
      text(x1, y, string.format("%d.%-12s %2d j", i, e.player:sub(1, 12),
           e.best), (i == 1) and "4" or "3")
      y = y + 1
    end
    if #top == 0 then text(x1, y, " personne encore", "8"); y = y + 1 end
  end

  if y + 1 <= L.y2 then
    y = y + 1
    rect(x1, y, x2, y, "e")
    center(x1, x2, y, "DERNIERS GAINS", "4", "e")
    for i, e in ipairs(DATA.last) do
      if y + i > L.y2 then break end
      text(x1, y + i, e.player:sub(1, 12) .. "  +" .. fmt(e.gain), "5")
    end
  end
end

--------------------------------------------------------------------------
-- ECRAN DE VEILLE
--------------------------------------------------------------------------
local PITCHES = {
  "C'est gratuit. Oui, gratuit.",
  "Un tour par jour, tous les jours.",
  "Trois jours d'affilee : roue d'argent.",
  "Sept jours d'affilee : roue Master Ball.",
  "Giovanni note ceux qui ne viennent pas.",
}

local STATE = { busy = false }

local function attractFrame(t)
  clear("f")
  drawBackdrop(t)
  local wheel = WHEELS.bronze
  local cyc = math.floor(t / 6) % 3
  if cyc == 1 then wheel = WHEELS.argent elseif cyc == 2 then wheel = WHEELS.master end
  drawWheel(wheel, t * 0.35, t)
  drawTitle(t, wheel)
  drawPanel(t, nil, nil, wheel, nil)
  drawPointer(wheel, t * 0.35)
  center(L.x1, L.wheelX2, L.y2 - 1,
         PITCHES[(math.floor(t / 4) % #PITCHES) + 1], "3")
  center(L.x1, L.wheelX2, L.y2,
         "INSCRIS-TOI SUR LE TERMINAL, PUIS TOUCHE L'ECRAN", "0")
  drawFrame(t)
  push()
end

local function attractLoop()
  while true do
    if not STATE.busy then pcall(attractFrame, os.clock()) end
    sleep(1 / 8)
  end
end

--------------------------------------------------------------------------
-- LE TOUR
--------------------------------------------------------------------------
local function spinOnce(wheel, player, streak)
  local n = #wheel.seg
  local seg = 2 * math.pi / n
  -- le resultat est tire d'abord, la rotation ne fait que l'illustrer
  local target = math.random(0, n - 1)

  -- angle final : le curseur (en haut) doit pointer le centre de la part
  local finalRot = (2 * math.pi - (target + 0.5) * seg) % (2 * math.pi)
  local turns = 4 + math.random(0, 2)
  local startRot = finalRot + 2 * math.pi * turns

  local t0 = os.clock()
  local timer = os.startTimer(1 / CFG.fps)
  local lastTick = 0
  while true do
    local ev, p1 = os.pullEvent()
    if ev == "timer" and p1 == timer then
      timer = os.startTimer(1 / CFG.fps)
      local el = os.clock() - t0
      local k = math.min(1, el / CFG.spinTime)
      local ease = 1 - (1 - k) ^ 3
      local rot = startRot + (finalRot - startRot) * ease

      -- claquement du curseur a chaque taquet
      local ticks = math.floor(((startRot - rot) / seg))
      if ticks > lastTick then
        lastTick = ticks
        beep(6 + (ticks % 8))
      end

      clear("f")
      drawBackdrop(os.clock())
      drawWheel(wheel, rot, os.clock())
      drawTitle(os.clock(), wheel)
      drawPanel(os.clock(), player, streak, wheel, nil)
      drawPointer(wheel, rot)
      center(L.x1, L.wheelX2, L.y2, "LA ROUE TOURNE...", "4")
      drawFrame(os.clock())
      push()

      if k >= 1 then return target, finalRot end
    end
  end
end

local function showResult(wheel, player, streak, target, rot, gain, extra)
  local v = wheel.seg[target + 1]
  local t0 = os.clock()
  while os.clock() - t0 < CFG.resultTime do
    local t = os.clock()
    clear("f")
    drawBackdrop(t)
    drawWheel(wheel, rot, t, target)
    drawTitle(t, wheel)
    drawPanel(t, player, streak, wheel, nil)
    drawPointer(wheel, rot)

    local msg, col
    if v == "MIAOUSS" then
      msg = "MIAOUSS FILE AVEC TA RECOMPENSE !"
      col = "e"
    elseif v == "REJOUE" then
      msg = "LA ROUE REPART !"
      col = "5"
    else
      msg = "+" .. fmt(gain) .. " CREDITS"
      col = "5"
    end
    local w = bigWidth(msg, 1)
    if w < (L.wheelX2 - L.x1) then
      local bx = math.floor((L.x1 + L.wheelX2) / 2 - w / 2)
      local by = L.y2 - 8
      if by > L.cy + L.ry then
        bigText(bx + 1, by + 1, msg, function() return "f" end)
        bigText(bx, by, msg, function()
          return (math.floor(t * 6) % 2 == 0) and "0" or col
        end)
      else
        -- pas la place sous la roue : bandeau plein au centre
        local by2 = L.cy - 1
        rect(L.x1, by2 - 1, L.wheelX2, by2 + 1, "f")
        center(L.x1, L.wheelX2, by2, msg,
               (math.floor(t * 6) % 2 == 0) and "0" or col)
      end
    else
      local by2 = L.cy - 1
      rect(L.x1, by2 - 1, L.wheelX2, by2 + 1, "f")
      center(L.x1, L.wheelX2, by2, msg, col)
    end
    if extra then center(L.x1, L.wheelX2, L.y2 - 1, extra, "4") end
    center(L.x1, L.wheelX2, L.y2, "Reviens demain a la meme heure !", "0")

    -- confettis sur un gros lot
    if gain and gain >= 500 then
      for i = 1, 50 do
        local sx = L.x1 + ((i * 31 + math.floor(t * 17)) % (L.wheelX2 - L.x1))
        local sy = L.y1 + L.headH +
                   ((i * 13 + math.floor(t * 11)) % (L.y2 - L.y1 - L.headH))
        px(sx, sy, ({ "4", "0", "e", "6" })[(i % 4) + 1])
      end
    end
    drawFrame(t, gain and gain >= 500)
    push()
    sleep(1 / CFG.fps)
  end
end

-- Tour complet : gere les relances et le vol de Miaouss
local function playTurn(player, streak)
  local wheel = wheelFor(streak)
  STATE.busy = true
  local total, spins = 0, 0
  local guard = 0

  repeat
    local target, rot = spinOnce(wheel, player, streak)
    local v = wheel.seg[target + 1]
    spins = spins + 1
    guard = guard + 1
    local gain, extra = 0, nil

    if v == "MIAOUSS" then
      gain = wheel.consol
      extra = "Il te laisse " .. gain .. " credits par pitie."
      beep(3, "bass")
    elseif v == "REJOUE" then
      extra = "Tour offert, la roue repart !"
      beep(18, "harp")
    else
      gain = v
      beep(20, "bell")
    end

    total = total + gain
    showResult(wheel, player, streak, target, rot, gain, extra)
  until v ~= "REJOUE" or guard >= 5

  STATE.busy = false
  return total, wheel
end

--------------------------------------------------------------------------
-- TERMINAL
--------------------------------------------------------------------------
local TW, TH = term.getSize()

local function tFill(y, bg)
  term.setBackgroundColor(bg)
  term.setCursorPos(1, y)
  term.write(string.rep(" ", TW))
end

local function tLabel(x, y, s, fg, bg)
  term.setCursorPos(x, y)
  term.setTextColor(fg)
  term.setBackgroundColor(bg or colors.black)
  term.write(s)
end

local function tCenter(y, s, fg, bg)
  tLabel(math.floor((TW - #s) / 2) + 1, y, s, fg, bg)
end

local function splash()
  term.setBackgroundColor(colors.black)
  term.clear()
  tFill(1, colors.red)
  tCenter(1, "ROUE ROCKET", colors.yellow, colors.red)
  tCenter(3, "UN TOUR GRATUIT PAR JOUR", colors.lime)
  tCenter(5, "Reviens chaque jour : ta serie monte", colors.white)
  tCenter(6, "3 jours = roue d'argent", colors.lightGray)
  tCenter(7, "7 jours = roue Master Ball", colors.lightGray)
  tCenter(9, "Rater 48 h remet la serie a zero", colors.orange)
  tCenter(TH - 2, "Une touche pour t'identifier", colors.yellow)
  while true do
    local ev = os.pullEvent()
    if ev == "key" or ev == "mouse_click" then return end
  end
end

local function session(player)
  while true do
    local can, waitMs, streak = status(player)
    term.setBackgroundColor(colors.black)
    term.clear()
    tFill(1, colors.red)
    tLabel(2, 1, "ROUE ROCKET", colors.yellow, colors.red)
    local p = DATA.players[player]
    local right = player .. "  serie " .. ((p and p.streak) or 0)
    tLabel(TW - #right, 1, right, colors.white, colors.red)

    if not can then
      tCenter(4, "Tu as deja tourne aujourd'hui.", colors.orange)
      tCenter(6, "Prochain tour dans " .. fmtDelay(waitMs), colors.yellow)
      tCenter(8, "Reviens demain a la meme heure", colors.white)
      tCenter(9, "pour garder ta serie de " .. ((p and p.streak) or 0) ..
              " jour(s).", colors.lightGray)
      tCenter(TH - 2, "Une touche pour revenir", colors.lightGray)
      os.pullEvent("key")
      return
    end

    local wheel = wheelFor(streak)
    tCenter(4, "TON TOUR EST DISPONIBLE", colors.lime)
    tCenter(6, "Serie : " .. streak .. " jour(s)  ->  roue " .. wheel.label,
            colors.yellow)
    tCenter(8, "VA TOUCHER LE MONITEUR POUR LANCER LA ROUE", colors.white)
    tCenter(10, "(tu as 60 secondes)", colors.gray)
    tFill(TH, colors.gray)
    tCenter(TH, "Q pour annuler", colors.lightGray, colors.gray)

    -- on attend le clic sur le moniteur
    STATE.busy = true
    clear("f")
    drawBackdrop(os.clock())
    drawWheel(wheel, 0, os.clock())
    drawTitle(os.clock(), wheel)
    drawPanel(os.clock(), player, streak, wheel, nil)
    drawPointer(wheel, 0)
    center(L.x1, L.wheelX2, L.y2 - 1, player .. ", touche l'ecran !", "4")
    center(L.x1, L.wheelX2, L.y2, "TON TOUR GRATUIT T'ATTEND", "5")
    drawFrame(os.clock(), true)
    push()

    local deadline = os.startTimer(60)
    local go = false
    while true do
      local ev, p1 = os.pullEvent()
      if ev == "monitor_touch" then go = true; break
      elseif ev == "timer" and p1 == deadline then break
      elseif ev == "key" and p1 == keys.q then break end
    end
    STATE.busy = false

    if not go then
      tCenter(12, "Tour annule, ton jeton est garde.", colors.orange)
      sleep(1.5)
      return
    end

    -- verrouillage AVANT de tourner : impossible de relancer
    recordSpin(player, streak, 0)
    local gain = playTurn(player, streak)
    if gain > 0 then bank.addBalance(player, gain) end
    -- on enregistre le gain reel
    local pp = DATA.players[player]
    pp.total = (pp.total or 0) + gain
    if DATA.last[1] then DATA.last[1].gain = gain end
    saveData(DATA)

    term.setBackgroundColor(colors.black)
    term.clear()
    tFill(1, colors.red)
    tCenter(1, "ROUE ROCKET", colors.yellow, colors.red)
    tCenter(4, "Tu as gagne " .. fmt(gain) .. " credits !", colors.lime)
    tCenter(6, "Serie portee a " .. streak .. " jour(s)", colors.yellow)
    local nw = wheelFor(streak + 1)
    if nw.label ~= wheelFor(streak).label then
      tCenter(8, "Demain tu passes sur la roue " .. nw.label .. " !",
              colors.orange)
    else
      tCenter(8, "Reviens demain a la meme heure.", colors.white)
    end
    tCenter(10, "Credit : " .. fmt(bank.getBalance(player)), colors.yellow)
    tCenter(TH - 2, "Une touche pour terminer", colors.lightGray)
    os.pullEvent("key")
    return
  end
end

--------------------------------------------------------------------------
-- PROGRAMME PRINCIPAL
--------------------------------------------------------------------------
math.randomseed((os.epoch and os.epoch("utc") or os.time()) % 2147483647)

print("=== Roue Rocket ===")
print("Moniteur : " .. W .. "x" .. H)
print("Un tour gratuit toutes les 24 h, series a 3 et 7 jours")

local function mainLoop()
  while true do
    splash()
    local player = login.authenticate("Connexion Roue Rocket")
    if player then session(player) end
  end
end

local ok, err = pcall(function()
  parallel.waitForAny(mainLoop, attractLoop)
end)

term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
term.setCursorPos(1, 1)
mon.setBackgroundColour(colours.black)
mon.clear()
if not ok and err ~= "Terminated" then error(err, 0) end
print("Roue Rocket : arret.")